<script setup lang="ts">
import { ref } from 'vue'
import RssAnimaListItem from '@/components/homepage/RssAnimeListItem.vue'
import { VTextField } from 'vuetify/components'
import {
  analysisRssRequest,
  rssAnalysisType,
  subscribeRssRequest,
  torrentFileType,
} from '@/api/rss.ts'
import { successAlert } from '@/store/alert.ts'
import AddDialogButtonGroup from '@/components/homepage/AddDialogButtonGroup.vue'
import AddDialogIncludeExclude from '@/components/homepage/AddDialogIncludeExclude.vue'

const Rules = {
  RSS: [
    (v: string) => !!v || '请输入RSS地址',
    (v: string) => {
      const pattern = new RegExp('^(http|https)://[^\\s]*$')
      return pattern.test(v) || '请输入正确的RSS地址'
    },
  ],
}

interface ComponentPropsType {
  Step: number
  isAnalysisStep: () => boolean
  isSubscribeStep: () => boolean
}
const ComponentProps = ref<ComponentPropsType>({
  Step: 0,
  isAnalysisStep: () => {
    return ComponentProps.value.Step === 0
  },
  isSubscribeStep: () => {
    return ComponentProps.value.Step === 1
  },
})

const isProcessingRequest = ref(false)
const viewFilelist = ref<torrentFileType[]>([])
const RssData = ref<rssAnalysisType>({
  title: '',
  season: '',
  searchedName: [],
  selectedSearchName: '',
  seasonNumber: 0,
  url: '',
  excludePatterns: [],
  includePatterns: [],
  fileList: [],
})

function updateSelected({ hash, value: selected }) {
  console.log(hash, selected)
  RssData.value.fileList.map((item) => {
    if (item.hash === hash) {
      item.isSelected = selected
    }
  })
}

function handlerAnalysis() {
  isProcessingRequest.value = true
  analysisRssRequest(RssData.value.url)
    .then((res) => {
      const data = res.data
      if (data) {
        RssData.value.title = data.title
        RssData.value.season = data.season
        RssData.value.seasonNumber = data.seasonNumber
        RssData.value.searchedName = data.searchedName
        RssData.value.fileList = data.fileList
        RssData.value.excludePatterns = data.excludePatterns
        RssData.value.includePatterns = data.includePatterns
        RssData.value.url = data.url
        viewFilelist.value = [...data.fileList]
        fileFilter()
        isProcessingRequest.value = false
        ComponentProps.value.Step = 1 //SubscribeStep
      }
    })
    .catch((err) => {
      console.log(err)
      isProcessingRequest.value = false
    })
}

const isAcitve = ref(false)
function closeDialog() {
  resetDialog()
  location.reload()
}

function resetDialog() {
  RssData.value = {
    title: '',
    season: '',
    url: '',
    seasonNumber: 0,
    selectedSearchName: '',
    searchedName: [],
    excludePatterns: [],
    includePatterns: [],
    fileList: [],
  }
  ComponentProps.value.Step = 0 //AnalysisRssStep
  isAcitve.value = false
}

function handlerSubscribe() {
  subscribeRssRequest(RssData.value)
    .then((res) => {
      console.log(res)
      closeDialog()
      successAlert('订阅成功')
    })
    .catch((err) => {
      console.log(err)
    })
}

function handlerFilter() {
  fileFilter()
}

function fileFilter() {
  let templist = RssData.value.fileList
  if (RssData.value.includePatterns.length > 0) {
    templist = templist.filter((item) => {
      return RssData.value.includePatterns.every((pattern) => {
        const matchword = item.name.includes(pattern)
        const matchregx = new RegExp(pattern).test(item.name)
        return matchword || matchregx
      })
    })
  }

  if (RssData.value.excludePatterns.length > 0) {
    templist = templist.filter((item) => {
      return RssData.value.excludePatterns.every((pattern) => {
        const matchword = !item.name.includes(pattern)
        const matchregx = !new RegExp(pattern).test(item.name)
        return matchword && matchregx
      })
    })
  }
  templist.sort((a, b) => a.name.localeCompare(b.name))

  viewFilelist.value = [...templist]
}
</script>

<template>
  <v-dialog
    v-model="isAcitve"
    persistent
    min-width="700"
    activator="parent"
    style="justify-self: left"
  >
    <template v-slot:default>
      <v-card
        prepend-icon="mdi-rss"
        title="订阅番剧"
        style="overflow-y: auto; max-height: 950px"
      >
        <v-overlay
          v-model="isProcessingRequest"
          contained
          opacity="0.5"
        ></v-overlay>
        <v-progress-circular
          v-if="isProcessingRequest"
          class="absolute-center"
          indeterminate
          size="74"
        ></v-progress-circular>
        <v-card-text v-show="ComponentProps.isAnalysisStep()">
          <v-text-field
            :rules="Rules.RSS"
            v-model="RssData.url"
            validate-on="blur"
            label="URL"
            outlined
            placeholder="请输入RSS地址"
          ></v-text-field>
        </v-card-text>

        <v-card-text
          style="min-width: 600px"
          v-show="ComponentProps.isSubscribeStep()"
        >
          <v-text-field
            label="番剧名称"
            v-model="RssData.title"
            outlined
            :placeholder="RssData.title"
          ></v-text-field>
          <v-select
            label="搜索名称"
            v-show="RssData.searchedName.length > 1"
            v-model="RssData.selectedSearchName"
            outlined
            :items="RssData.searchedName"
          ></v-select>
          <v-text-field
            label="季度"
            v-model="RssData.season"
            outlined
            :placeholder="RssData.season"
          ></v-text-field>

          <AddDialogIncludeExclude
            :rss-data="RssData"
            @filter="handlerFilter"
          ></AddDialogIncludeExclude>

          <v-list class="rssanimalist">
            <v-list-subheader style="user-select: none">文件</v-list-subheader>
            <RssAnimaListItem
              v-for="(file, index) in viewFilelist"
              :key="index"
              v-bind="file"
              @update:isSelected="updateSelected"
            ></RssAnimaListItem>
          </v-list>
        </v-card-text>

        <v-card-actions>
          <v-spacer></v-spacer>
          <AddDialogButtonGroup
            :rules="Rules.RSS"
            v-bind="ComponentProps"
            :url="RssData.url"
            @analysis="handlerAnalysis"
            @close="closeDialog"
            @subscribe="handlerSubscribe"
          ></AddDialogButtonGroup>
        </v-card-actions>
      </v-card>
    </template>
  </v-dialog>
</template>

<style scoped>
.rssanimalist {
  margin-bottom: 30px;
  border: 1px solid gray;
  padding: 10px;
  overflow: auto;
  height: 350px;
}
.absolute-center {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
</style>
